<?php

namespace App\Http\Controllers;

use App\Http\Requests\ResultGames\UpdateRequest;
use App\Models\ResultGames;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class GameController extends Controller
{
    private $playerName = 'Player';

    public function index()
    {
        return view('main');
    }

    public function game()
    {
        return view('game');
    }

    public function play(Request $request)
    {
        $playerChoice = $request->input('player_choice');

        $botChoice = rand(1, 3);
        if ($botChoice == 1) {
            $botChoice = 'rock';
        } elseif ($botChoice == 2) {
            $botChoice = 'paper';
        } else {
            $botChoice = 'scissors';
        }

        if (($playerChoice == 'rock' and $botChoice == 'scissors') or ($playerChoice == 'scissors' and $botChoice == 'paper') or ($playerChoice == 'paper' and $botChoice == 'rock')) {
            $result = 'You win!';
        } elseif ($playerChoice == $botChoice) {
            $result = 'Tie!';
        } else {
            $result = 'You lose!';
        }

        DB::table('result_games')->insert([
            'player_name' => $this->playerName, 
            'player_choice' => $playerChoice,
            'bot_choice' => $botChoice,
            'result' => $result,
            'created_at' => now(),
            'updated_at' => now()
        ]);
        return view('game', ['result' => $result]);
    }

    public function info()
    {
        $playerName = session('player_name', 'Player');
        $results = ResultGames::paginate(26);
        return view('statistic', compact('results', 'playerName'));
    }

    public function edit(ResultGames $resultGames)
    {
        return view('edit', compact('resultGames'));
    }

    public function update(UpdateRequest $request, ResultGames $resultGames)
    {
        $input = $request->validated();

        $resultGames->update($input);
        $this->playerName = $input['player_name'];

        session(['player_name' => $input['player_name']]);

        return redirect()->route('main.index');
    }


        
}
